<template>
  <a-card title="编辑房户信息" style="width: 600px; pointer-events: all">
    <template #extra>
      <a-select ref="select" v-model:value="selectBuild"  placeholder="请选择楼栋" style="width: 120px" :options="buildsOption"   @change="handleChange"></a-select>
    </template>
    <a-table size="small" bordered :data-source="houseList" :loading="loading" :columns="buildingColumns" :pagination="pagination" @change="handlePaginationChange">
      <template #bodyCell="{ column, text, record }">
        <!-- 只有当 column.dataIndex 的值是指定的这三个之一时，才渲染里面的内容 -->
        <template v-if="['doorNumText', 'floorNumText', 'numberText'].includes(column.dataIndex)">
          <a-tag :color="column.dataIndex === 'doorNumText' ? 'red' : 'green'">{{ text }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a @click="edit(record)">编辑信息</a>
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'positionFix'">
          <div @click="focusOnArea(record)">
            <img style="cursor: pointer" width="20" height="20" src="/src/assets/position.png" alt="" />
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <FormInfo :formData="formData" :formOpen="formOpen" @onClose="onClose" />
</template>

<script setup>
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
import { getBuild, getHouse, getOneHouseInfo } from '@/api/api'
import { ref, onMounted, reactive, onBeforeUnmount } from 'vue'
import FormInfo from './FormInfo.vue'
import { useMapData } from '@/store'

const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const selectBuild = ref(null)
const buildsOption = ref([])
const formData = ref({})
const formOpen = ref(false)
const loading = ref(false)
const currentBuild = ref(null)
const pagination = reactive({
  total: 0,
  current: 0,
  pageSize: 0,
})

const buildingColumns = ref([
  {
    title: '门牌号',
    dataIndex: 'doorNumText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '单元号',
    dataIndex: 'numberText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '楼层',
    dataIndex: 'floorNumText',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    ellipsis: true,
  },
  {
    title: '定位',
    dataIndex: 'positionFix',
    align: 'center',
    width: '10%',
  },
])

// 楼栋信息
const houseList = ref([])
// 当前渲染的图元
let primitiveHouse
let currentBuildEnt
onMounted(async () => {
  const buildInfo = await getBuild()
  if (buildInfo?.code === 200) {
    buildsOption.value = buildInfo.data.map((item) => {
      return {
        value: item.id,
        label: item.name,
        polygon: item.polygon,
      }
    })
  }
})

onBeforeUnmount(() => {
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse)
  currentBuildEnt && viewer.entities.remove(currentBuildEnt)
  currentBuildEnt = null
  primitiveHouse = null
})

// 选中楼栋。渲染表格，并在地图上添加实体，展示楼栋
const handleChange = (e) => {
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse)
  currentBuildEnt && viewer.entities.remove(currentBuildEnt)
  currentBuildEnt = null
  primitiveHouse = null
  // 渲染entity，包裹楼栋
  const target = buildsOption.value.find((item) => item.value === e)
  if (target) {
    const { polygon } = target
    const center = turf.center(polygon)
    // 使用flat()将数组拍平
    // 最终得到coordinates = [lon1, lat1, lon2, lat2, lon3, lat3, ...] 这是 Cesium 中 Cartesian3.fromDegreesArray() 需要的格式：
    const coordinates = polygon.coordinates[0].flat()
    currentBuildEnt = viewer.entities.add({
      name: target.label,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(new Cesium.Cartesian3.fromDegreesArray(coordinates)),
        material: Cesium.Color.RED.withAlpha(0.6),
        // classificationType 在 Cesium 中，某些图元（如 Entity 的 polygon 或 ClassificationPrimitive）可以“分类”地图上的元素，也就是将其“投影”到地形或 3D Tiles 上。
        // Cesium.ClassificationType.TERRAIN      // 只影响地形（terrain）
        // Cesium.ClassificationType.CESIUM_3D_TILE // 只影响 3D Tiles
        // Cesium.ClassificationType.BOTH         // 同时影响地形和 3D Tiles（默认）
        classificationType: Cesium.ClassificationType.BOTH,
      },
    })

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(...center.geometry.coordinates, 200),
    })
    currentBuild.value = e
    const queryParam = {
      id: e,
      pageIndex: 1,
    }
    getHouseData(queryParam)
  }
}

const getHouseData = async (param) => {
  loading.value = true
  const res = await getHouse(param)
  console.log(res)
  if (res.code == 200) {
    houseList.value = res.data.list.map((item) => {
      // 构造门牌号
      const doorNumText = `${item.floorNum}-0${item.number}`
      // 构造单元号
      const numberText = `${item.number}单元`
      // 构造楼层
      const floorNumText = `${item.floorNum}楼`
      return {
        ...item,
        doorNumText,
        numberText,
        floorNumText,
      }
    })
    pagination.total = res.data.total
    pagination.pageSize = houseList.value.length
    pagination.current = param.pageIndex
  }
  loading.value = false
}

const focusOnArea = (record) => {
  console.log(record)
  primitiveHouse && viewer.scene.primitives.remove(primitiveHouse)
  if (record) {
    const { polygon, minHeight, maxHeight } = record
    const coordinates = polygon.coordinates[0].flat() // 拍平数组,以符合传入要求
    primitiveHouse = new Cesium.ClassificationPrimitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.PolygonGeometry({
          polygonHierarchy: new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(coordinates)),
          height: minHeight,
          extrudedHeight: maxHeight,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW.withAlpha(0.8)),
        },
      }),
      classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
    })
    viewer.scene.primitives.add(primitiveHouse)
  }
}

const edit = async (data) => {
  const { id, number, floorNum } = data
  const res = await getOneHouseInfo({ id })
  if (res?.code === 200) {
    formOpen.value = true
    let houseNum = number > 9 ? number : '0' + number
    const houseAddress = number + '单元' + floorNum + houseNum
    res.data.houseAddress = houseAddress
    res.data.id = id
    formData.value = res.data
  }
}

const onClose = () => {
  formOpen.value = false
}

const handlePaginationChange = (pagination) => {
  const { current } = pagination
  console.log(current)
  const queryParam = {
    id: currentBuild.value,
    pageIndex: current,
  }
  getHouseData(queryParam)
}
</script>
<style scoped lang="less"></style>
